package zy.service.buy.enter.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import zy.dao.approve.ApproveRecordDAO;
import zy.dao.base.depot.DepotDAO;
import zy.dao.base.product.ProductDAO;
import zy.dao.base.size.SizeDAO;
import zy.dao.buy.dealings.BuyDealingsDAO;
import zy.dao.buy.enter.EnterDAO;
import zy.dao.buy.settle.BuySettleDAO;
import zy.dao.buy.supply.SupplyDAO;
import zy.dao.stock.data.DataDAO;
import zy.dao.stock.useable.UseableDAO;
import zy.dao.sys.print.PrintDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.approve.T_Approve_Record;
import zy.entity.base.product.T_Base_Barcode;
import zy.entity.base.product.T_Base_Product;
import zy.entity.base.size.T_Base_Size;
import zy.entity.base.size.T_Base_SizeList;
import zy.entity.buy.dealings.T_Buy_Dealings;
import zy.entity.buy.enter.T_Buy_Enter;
import zy.entity.buy.enter.T_Buy_EnterList;
import zy.entity.buy.order.T_Buy_Import;
import zy.entity.buy.order.T_Buy_Order;
import zy.entity.buy.order.T_Buy_Product;
import zy.entity.buy.settle.T_Buy_SettleList;
import zy.entity.buy.supply.T_Buy_Supply;
import zy.entity.stock.data.T_Stock_DataBill;
import zy.entity.sys.set.T_Sys_Set;
import zy.entity.sys.user.T_Sys_User;
import zy.service.buy.enter.EnterService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;
import zy.vo.buy.BuyVO;
import zy.vo.common.SizeHorizontalVO;

@Service
public class EnterServiceImpl implements EnterService{
	
	@Resource
	private EnterDAO enterDAO;
	
	@Resource
	private SizeDAO sizeDAO;
	
	@Resource
	private ApproveRecordDAO approveRecordDAO;
	
	@Resource
	private DataDAO dataDAO;
	
	@Resource
	private BuyDealingsDAO buyDealingsDAO;
	
	@Resource
	private BuySettleDAO buySettleDAO;
	
	@Resource
	private PrintDAO printDAO;
	
	@Resource
	private SupplyDAO supplyDAO;
	
	@Resource
	private UseableDAO useableDAO;
	
	@Resource
	private ProductDAO productDAO;
	
	@Resource
	private DepotDAO depotDAO;

	@Override
	public PageData<T_Buy_Enter> page(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		if(CommonUtil.THREE.equals(params.get(CommonUtil.SHOP_TYPE))){//自营店
			params.put("depot_codes", depotDAO.listDepotByShop(params.get(CommonUtil.SHOP_CODE).toString(), companyid));
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Map<String, Object> sumMap = enterDAO.countSum(params);
		int totalCount = Integer.parseInt(sumMap.get("totalCount").toString());
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<T_Buy_Enter> list = enterDAO.list(params);
		PageData<T_Buy_Enter> pageData = new PageData<T_Buy_Enter>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		pageData.setData(sumMap);
		return pageData;
	}
	
	@Override
	public List<T_Buy_Enter> listExport(Map<String, Object> params) {
		Assert.notNull(params.get(CommonUtil.COMPANYID),"连接超时，请重新登录!");
		params.put(CommonUtil.START, 0);
		params.put(CommonUtil.END, Integer.MAX_VALUE);
		return enterDAO.list(params);
	}
	
	@Override
	public T_Buy_Enter load(Integer et_id) {
		T_Buy_Enter enter = enterDAO.load(et_id);
		if(enter != null){
			T_Approve_Record approve_Record = approveRecordDAO.load(enter.getEt_number(), enter.getCompanyid());
			if(approve_Record != null){
				enter.setAr_describe(approve_Record.getAr_describe());
			}
		}
		return enter;
	}
	
	@Override
	public T_Buy_Enter load(String number,Integer companyid) {
		return enterDAO.load(number, companyid);
	}
	
	@Override
	public List<T_Buy_EnterList> detail_list(Map<String, Object> params) {
		return enterDAO.detail_list(params);
	}
	
	@Override
	public List<T_Buy_EnterList> detail_sum(Map<String, Object> params) {
		return enterDAO.detail_sum(params);
	}
	
	@Override
	public Map<String, Object> detail_size_title(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = enterDAO.detail_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("titles", new ArrayList<List<String>>());
			return resultMap;
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		return SizeHorizontalVO.getJsonSizeTitles(sizeGroupList);
	}
	
	@Override
	public Map<String, Object> detail_size(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = enterDAO.detail_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			return new HashMap<String, Object>();
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		params.put(CommonUtil.SIDX, "etl_pd_code,etl_pi_type,etl_cr_code,etl_br_code");
		params.put(CommonUtil.SORD, "ASC");
		List<T_Buy_EnterList> temps = enterDAO.detail_list(params);
		return BuyVO.getJsonSizeData_Enter(sizeGroupList, temps);
	}
	
	@Override
	public List<T_Buy_EnterList> temp_list(Map<String, Object> params) {
		return enterDAO.temp_list(params);
	}
	
	@Override
	public List<T_Buy_EnterList> temp_sum(Map<String, Object> params) {
		return enterDAO.temp_sum(params);
	}
	
	@Override
	public Map<String, Object> temp_size_title(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = enterDAO.temp_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("titles", new ArrayList<List<String>>());
			return resultMap;
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		return SizeHorizontalVO.getJsonSizeTitles(sizeGroupList);
	}
	
	@Override
	public Map<String, Object> temp_size(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = enterDAO.temp_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			return new HashMap<String, Object>();
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		params.put(CommonUtil.SIDX, "etl_pd_code,etl_pi_type,etl_cr_code,etl_br_code");
		params.put(CommonUtil.SORD, "ASC");
		List<T_Buy_EnterList> temps = enterDAO.temp_list(params);
		return BuyVO.getJsonSizeData_Enter(sizeGroupList, temps);
	}

	@Override
	@Transactional
	public Map<String, Object> temp_save_bybarcode(Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Integer et_type = (Integer)params.get("et_type");
		String barcode = (String)params.get("barcode");
		Integer amount = (Integer)params.get("amount");
		Integer priceType = (Integer)params.get("priceType");
		Double sp_rate = (Double)params.get("sp_rate");
		T_Sys_User user = (T_Sys_User)params.get("user");
		T_Base_Barcode base_Barcode = productDAO.loadBarcode(barcode, user.getCompanyid());
		if(base_Barcode == null){
			resultMap.put("result", 3);//条码不存在
			return resultMap;
		}
		T_Buy_EnterList temp = enterDAO.temp_loadBySubCode(base_Barcode.getBc_subcode(), "0", et_type, user.getUs_id(), user.getCompanyid());
		if (temp != null) {//临时表存在则直接更新数量
			temp.setEtl_amount(temp.getEtl_amount()+amount);
			enterDAO.temp_update(temp);
			resultMap.put("result", 1);//update
			resultMap.put("temp", temp);
			return resultMap;
		}
		T_Base_Product base_Product = enterDAO.load_product(base_Barcode.getBc_pd_code(), user.getCompanyid());
		Double unitPrice = enterDAO.temp_queryUnitPrice(base_Barcode.getBc_pd_code(),"0", et_type, user.getUs_id(), user.getCompanyid());;
		if(unitPrice == null){
			if("1".equals(priceType)){//最后一次进价
				unitPrice = base_Product.getPd_buy_price();
			}else {//按照折扣率
				unitPrice = base_Product.getPd_sell_price() * sp_rate;
			}
		}
		temp = new T_Buy_EnterList();
		temp.setEtl_pd_code(base_Barcode.getBc_pd_code());
		temp.setEtl_cr_code(base_Barcode.getBc_color());
		temp.setEtl_sz_code(base_Barcode.getBc_size());
		temp.setEtl_szg_code(base_Product.getPd_szg_code());
		temp.setEtl_br_code(base_Barcode.getBc_bra());
		temp.setEtl_sub_code(temp.getEtl_pd_code()+temp.getEtl_cr_code()+temp.getEtl_sz_code()+temp.getEtl_br_code());
		temp.setEtl_amount(amount);
		temp.setEtl_unitprice(unitPrice);
		temp.setEtl_retailprice(base_Product.getPd_sell_price());
		temp.setEtl_remark("");
		temp.setEtl_pi_type(0);//商品
		temp.setEtl_type(et_type);
		temp.setEtl_us_id(user.getUs_id());
		temp.setCompanyid(user.getCompanyid());
		enterDAO.temp_save(temp);
		temp.setPd_no(base_Product.getPd_no());
		temp.setPd_name(base_Product.getPd_name());
		temp.setPd_unit(base_Product.getPd_unit());
		temp.setBd_name(base_Product.getPd_bd_name());
		temp.setTp_name(base_Product.getPd_tp_name());
		temp.setCr_name(base_Barcode.getBc_colorname());
		temp.setSz_name(base_Barcode.getBc_sizename());
		temp.setBr_name(base_Barcode.getBc_braname());
		resultMap.put("result", 2);//add
		resultMap.put("temp", temp);
		return resultMap;
	}
	
	@Override
	public PageData<T_Base_Product> page_product(Map<String, Object> param) {
		Object companyid = param.get(CommonUtil.COMPANYID);
		Object pageSize = param.get(CommonUtil.PAGESIZE);
		Object pageIndex = param.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = enterDAO.count_product(param);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		param.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		param.put(CommonUtil.END, _pageSize);
		
		List<T_Base_Product> list = enterDAO.list_product(param);
		PageData<T_Base_Product> pageData = new PageData<T_Base_Product>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> temp_loadproduct(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		T_Sys_Set sysSet = (T_Sys_Set)params.get(CommonUtil.KEY_SYSSET);
		Integer us_id = (Integer)params.get("us_id");
		String pd_code = (String)params.get("pd_code");
		String dp_code = (String)params.get("dp_code");
		String priceType = (String)params.get("priceType");
		Double sp_rate = (Double)params.get("sp_rate");
		Integer et_type = (Integer)params.get("et_type");
		String exist = (String)params.get("exist");
		String etl_pi_type = (String)params.get("etl_pi_type");
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		T_Base_Product base_Product = enterDAO.load_product(pd_code, companyid);
		Map<String, Object> product = new HashMap<String, Object>();
		product.put("pd_id", base_Product.getPd_id());
		product.put("pd_code", base_Product.getPd_code());
		product.put("pd_no", base_Product.getPd_no());
		product.put("pd_name", base_Product.getPd_name());
		product.put("pd_szg_code", base_Product.getPd_szg_code());
		product.put("pd_unit", base_Product.getPd_unit());
		product.put("pd_year", base_Product.getPd_year());
		product.put("pd_season", base_Product.getPd_season());
		product.put("pd_sell_price", base_Product.getPd_sell_price());
		product.put("pdm_buy_price", base_Product.getPd_buy_price());
		product.put("pd_bd_name", base_Product.getPd_bd_name());
		product.put("pd_tp_name", base_Product.getPd_tp_name());
		product.put("pdm_img_path", StringUtil.trimString(base_Product.getPdm_img_path()));
		Double unitPrice = null;
		if("1".equals(exist)){//已经录入从临时表中查询单价
			unitPrice = enterDAO.temp_queryUnitPrice(pd_code,etl_pi_type, et_type, us_id, companyid);
			product.put("temp_unitPrice", StringUtil.trimString(unitPrice));
		}
		if(unitPrice == null){
			if("1".equals(priceType)){//最后一次进价
				unitPrice = base_Product.getPd_buy_price();
			}else {//按照折扣率
				unitPrice = base_Product.getPd_sell_price() * sp_rate;
			}
		}
		product.put("unitPrice", unitPrice);
		resultMap.put("product", product);
		params.put("szg_code", base_Product.getPd_szg_code());
		Map<String, Object> productMap = enterDAO.load_product_size(params);
		List<T_Base_Size> sizes=(List<T_Base_Size>)productMap.get("sizes");
		List<T_Buy_Product> inputs=(List<T_Buy_Product>)productMap.get("inputs");
		List<T_Buy_Product> temps=(List<T_Buy_Product>)productMap.get("temps");
		List<T_Buy_Product> stocks=(List<T_Buy_Product>)productMap.get("stocks");
		Map<String,Object> usableStockMap = null;
		if (sysSet.getSt_useable() != null && sysSet.getSt_useable().intValue() == 1) {
			usableStockMap = useableDAO.loadUseableStock(pd_code, dp_code, companyid);
		}
		resultMap.putAll(BuyVO.buildJsonProductInput(pd_code, sizes, inputs, stocks, temps, usableStockMap));
		return resultMap;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public void temp_save(Map<String, Object> params) {
		List<T_Buy_EnterList> temps = (List<T_Buy_EnterList>)params.get("temps");
		Integer et_type = (Integer)params.get("et_type");
		T_Sys_User user = (T_Sys_User)params.get("user");
		Object pd_code = params.get("pd_code");
		Object unitPrice = params.get("unitPrice");
		if (temps != null && temps.size() > 0) {
			List<T_Buy_EnterList> temps_add = new ArrayList<T_Buy_EnterList>();
			List<T_Buy_EnterList> temps_update = new ArrayList<T_Buy_EnterList>();
			List<T_Buy_EnterList> temps_del = new ArrayList<T_Buy_EnterList>();
			for (T_Buy_EnterList item : temps) {
				if ("add".equals(item.getOperate_type())){
					if (item.getEtl_amount() > 0) {
						temps_add.add(item);
					}
				}else if("update".equals(item.getOperate_type())){
					if(!item.getEtl_amount().equals(0)){
						temps_update.add(item);
					}else {
						temps_del.add(item);
					}
				}
			}
			if (temps_add.size() > 0) {
				enterDAO.temp_save(temps_add);
			}
			if (temps_update.size() > 0) {
				enterDAO.temp_update(temps_update);
			}
			if (temps_del.size() > 0) {
				enterDAO.temp_del(temps_del);
			}
		}
		if (StringUtil.isNotEmpty(pd_code) && StringUtil.isNotEmpty(unitPrice)) {
			enterDAO.temp_updateprice(pd_code.toString(),"0", Double.parseDouble(unitPrice.toString()), et_type, user.getUs_id(), user.getCompanyid());
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public void temp_import(Map<String, Object> params) {
		List<String[]> datas = (List<String[]>)params.get("datas");
		Integer et_type = (Integer)params.get("et_type");
		T_Sys_User user = (T_Sys_User)params.get("user");
		Object priceType = params.get("priceType");
		Object sp_rate = params.get("sp_rate");
		List<String> barcodes = new ArrayList<String>();
		Map<String, Integer> data_amount = new HashMap<String, Integer>();
		for (String[] data : datas) {
			barcodes.add(data[0]);
			data_amount.put(data[0], Integer.parseInt(data[1]));
		}
		List<T_Buy_Import> imports = enterDAO.temp_listByImport(barcodes, user.getCompanyid());
		if (imports == null || imports.size() == 0) {
			throw new RuntimeException("无数据可导入");
		}
		Map<String, Double> unitPriceMap = new HashMap<String, Double>();
		Map<String, T_Buy_EnterList> tempsMap = new HashMap<String, T_Buy_EnterList>();
		List<T_Buy_EnterList> temps = enterDAO.temp_list_forimport(et_type, user.getUs_id(), user.getCompanyid());
		for (T_Buy_EnterList temp : temps) {
			if(!unitPriceMap.containsKey(temp.getEtl_pd_code())){
				unitPriceMap.put(temp.getEtl_pd_code(), temp.getEtl_unitprice());
			}
			tempsMap.put(temp.getEtl_sub_code(), temp);
		}
		List<T_Buy_EnterList> temps_add = new ArrayList<T_Buy_EnterList>();
		List<T_Buy_EnterList> temps_update = new ArrayList<T_Buy_EnterList>();
		for (T_Buy_Import item : imports) {
			if(tempsMap.containsKey(item.getBc_subcode())){//临时表已存在，更新数量
				T_Buy_EnterList temp = tempsMap.get(item.getBc_subcode());
				temp.setEtl_amount(temp.getEtl_amount()+data_amount.get(item.getBc_barcode()));
				temps_update.add(temp);
			}else {//临时表不存在，新增数据
				T_Buy_EnterList temp = new T_Buy_EnterList();
				temp.setEtl_pd_code(item.getBc_pd_code());
				temp.setEtl_sub_code(item.getBc_subcode());
				temp.setEtl_sz_code(item.getBc_size());
				temp.setEtl_szg_code(item.getPd_szg_code());
				temp.setEtl_cr_code(item.getBc_color());
				temp.setEtl_br_code(item.getBc_bra());
				temp.setEtl_amount(data_amount.get(item.getBc_barcode()));
				if(unitPriceMap.containsKey(item.getBc_pd_code())){//临时表已存在此货号，则使用临时表价格
					temp.setEtl_unitprice(unitPriceMap.get(item.getBc_pd_code()));
				}else{
					if("1".equals(priceType)){//最后一次进价
						temp.setEtl_unitprice(item.getUnit_price());
					}else {//按照折扣率
						temp.setEtl_unitprice(item.getRetail_price()* Double.parseDouble(StringUtil.trimString(sp_rate)));
					}
				}
				temp.setEtl_retailprice(item.getRetail_price());
				temp.setEtl_remark("");
				temp.setEtl_pi_type(0);//商品
				temp.setEtl_us_id(user.getUs_id());
				temp.setEtl_type(et_type);
				temp.setCompanyid(user.getCompanyid());
				temps_add.add(temp);
			}
		}
		if (temps_add.size() > 0) {
			enterDAO.temp_save(temps_add);
		}
		if (temps_update.size() > 0) {
			enterDAO.temp_updateById(temps_update);
		}
	}
	
	@Override
	@Transactional
	public void temp_import_draft(Map<String, Object> params) {
		String et_number = (String)params.get("et_number");
		Integer et_type = (Integer)params.get("et_type");
		T_Sys_User user = (T_Sys_User)params.get("user");
		List<T_Buy_EnterList> details = enterDAO.detail_list_forsavetemp(et_number,user.getCompanyid());
		if (details == null || details.size() == 0) {
			throw new RuntimeException("草稿不存在");
		}
		for(T_Buy_EnterList item:details){
			item.setEtl_us_id(user.getUs_id());
		}
		enterDAO.temp_clear(et_type, user.getUs_id(), user.getCompanyid());
		enterDAO.temp_save(details);
		enterDAO.del(et_number, user.getCompanyid());
	}
	
	@Override
	@Transactional
	public void temp_import_order(Map<String, Object> params) {
		String ids = (String)params.get("ids");
		if(StringUtil.isEmpty(ids)){
			throw new IllegalArgumentException("参数ids不能为null");
		}
		List<Integer> odl_ids = new ArrayList<Integer>();
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			odl_ids.add(Integer.parseInt(id));
		}
		Integer et_type = (Integer)params.get("et_type");
		T_Sys_User user = (T_Sys_User)params.get("user");
		List<T_Buy_EnterList> details = enterDAO.list_order_forimport(odl_ids);
		if (details == null || details.size() == 0) {
			throw new RuntimeException("草稿不存在");
		}
		for(T_Buy_EnterList item:details){
			item.setEtl_us_id(user.getUs_id());
		}
		enterDAO.temp_clear(et_type, user.getUs_id(), user.getCompanyid());
		enterDAO.temp_save(details);
	}
	
	@Override
	@Transactional
	public void temp_updateAmount(T_Buy_EnterList temp) {
		enterDAO.temp_update(temp);
	}
	
	@Override
	@Transactional
	public void temp_updatePrice(T_Buy_EnterList temp) {
		enterDAO.temp_updateprice(temp.getEtl_pd_code(), StringUtil.trimString(temp.getEtl_pi_type()),
				temp.getEtl_unitprice(), temp.getEtl_type(),
				temp.getEtl_us_id(), temp.getCompanyid());
	}
	
	@Override
	@Transactional
	public void temp_updateRemarkById(T_Buy_EnterList temp) {
		enterDAO.temp_updateRemarkById(temp);
	}
	
	@Override
	@Transactional
	public void temp_updateRemarkByPdCode(T_Buy_EnterList temp) {
		enterDAO.temp_updateRemarkByPdCode(temp);
	}
	
	@Override
	@Transactional
	public void temp_del(Integer etl_id) {
		enterDAO.temp_del(etl_id);
	}
	
	@Override
	@Transactional
	public void temp_delByPiCode(T_Buy_EnterList temp) {
		if (temp.getCompanyid() == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		if (temp.getEtl_us_id() == null) {
			throw new IllegalArgumentException("参数us_id不能为null");
		}
		if (temp.getEtl_type() == null) {
			throw new IllegalArgumentException("参数etl_type不能为null");
		}
		enterDAO.temp_delByPiCode(temp);
	}
	
	@Override
	@Transactional
	public void temp_clear(Integer et_type,Integer us_id,Integer companyid) {
		enterDAO.temp_clear(et_type, us_id, companyid);;
	}
	
	@Override
	@Transactional
	public void save(T_Buy_Enter enter, T_Sys_User user) {
		if(enter == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(enter.getEt_supply_code())){
			throw new IllegalArgumentException("供应商不能为空");
		}
		if(StringUtil.isEmpty(enter.getEt_depot_code())){
			throw new IllegalArgumentException("仓库不能为空");
		}
		if(StringUtil.isEmpty(enter.getEt_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		enter.setCompanyid(user.getCompanyid());
		enter.setEt_us_id(user.getUs_id());
		enter.setEt_maker(user.getUs_name());
		enter.setEt_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		enter.setEt_sysdate(DateUtil.getCurrentTime());
		enter.setEt_pay_state(0);
		enter.setEt_payabled(0d);
		enter.setEt_prepay(0d);
		enter.setEt_order_number("");
		
		//1.查临时表
		List<T_Buy_EnterList> temps = enterDAO.temp_list_forsave(enter.getEt_type(), user.getUs_id(), user.getCompanyid());
		if(temps == null || temps.size() == 0){
			throw new RuntimeException("单据已保存，请勿重复提交");
		}
		//2.保存主表
		for(T_Buy_EnterList temp:temps){
			if(StringUtil.isNotEmpty(temp.getEtl_order_number())){
				enter.setEt_order_number(temp.getEtl_order_number());
				break;
			}
		}
		if(enter.getEt_type().equals(1)){//退货
			for (T_Buy_EnterList temp : temps) {
				temp.setEtl_amount(-Math.abs(temp.getEtl_amount()));
			}
		}
		int et_amount = 0;
		double et_money = 0d;
		double et_retailmoney = 0d;
		for (T_Buy_EnterList temp : temps) {
			et_amount += temp.getEtl_amount();
			et_money += temp.getEtl_amount() * temp.getEtl_unitprice();
			et_retailmoney += temp.getEtl_amount() * temp.getEtl_retailprice();
		}
		enter.setEt_discount_money(enter.getEt_discount_money() == null ? 0d : enter.getEt_discount_money());
		enter.setEt_amount(et_amount);
		enter.setEt_money(et_money);
		enter.setEt_retailmoney(et_retailmoney);
		enter.setEt_payable(enter.getEt_money() - enter.getEt_discount_money());
		enterDAO.save(enter);
		//2.保存明细子表
		for (T_Buy_EnterList temp : temps) {
			temp.setEtl_number(enter.getEt_number());
		}
		enterDAO.saveList(temps);
		//3.删除临时表
		enterDAO.temp_clear(enter.getEt_type(), user.getUs_id(), user.getCompanyid());
	}
	
	@Override
	@Transactional
	public void update(T_Buy_Enter enter, T_Sys_User user) {
		if(enter == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(enter.getEt_supply_code())){
			throw new IllegalArgumentException("供应商不能为空");
		}
		if(StringUtil.isEmpty(enter.getEt_depot_code())){
			throw new IllegalArgumentException("仓库不能为空");
		}
		if(StringUtil.isEmpty(enter.getEt_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		enter.setCompanyid(user.getCompanyid());
		enter.setEt_us_id(user.getUs_id());
		enter.setEt_maker(user.getUs_name());
		enter.setEt_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		enter.setEt_sysdate(DateUtil.getCurrentTime());
		enter.setEt_pay_state(0);
		enter.setEt_payabled(0d);
		enter.setEt_prepay(0d);
		enter.setEt_order_number("");
		
		//1.1查临时表
		List<T_Buy_EnterList> temps = enterDAO.temp_list_forsave(enter.getEt_type(), user.getUs_id(), user.getCompanyid());
		if(temps == null || temps.size() == 0){
			throw new RuntimeException("单据已保存，请勿重复提交");
		}
		//1.2验证单据
		T_Buy_Enter oldEnter = enterDAO.check(enter.getEt_number(), user.getCompanyid());
		if (oldEnter == null || !CommonUtil.AR_STATE_FAIL.equals(oldEnter.getEt_ar_state())) {
			throw new RuntimeException("单据已修改，请勿重复提交");
		}
		//1.3删除子表
		enterDAO.deleteList(enter.getEt_number(), user.getCompanyid());
		
		//2.保存主表
		for(T_Buy_EnterList temp:temps){
			if(StringUtil.isNotEmpty(temp.getEtl_order_number())){
				enter.setEt_order_number(temp.getEtl_order_number());
				break;
			}
		}
		if(enter.getEt_type().equals(1)){//退货
			for (T_Buy_EnterList temp : temps) {
				temp.setEtl_amount(-Math.abs(temp.getEtl_amount()));
			}
		}
		int et_amount = 0;
		double et_money = 0d;
		double et_retailmoney = 0d;
		for (T_Buy_EnterList temp : temps) {
			et_amount += temp.getEtl_amount();
			et_money += temp.getEtl_amount() * temp.getEtl_unitprice();
			et_retailmoney += temp.getEtl_amount() * temp.getEtl_retailprice();
		}
		enter.setEt_discount_money(enter.getEt_discount_money() == null ? 0d : enter.getEt_discount_money());
		enter.setEt_amount(et_amount);
		enter.setEt_money(et_money);
		enter.setEt_retailmoney(et_retailmoney);
		enter.setEt_payable(enter.getEt_money() - enter.getEt_discount_money());
		enterDAO.update(enter);
		//2.保存明细子表
		for (T_Buy_EnterList temp : temps) {
			temp.setEtl_number(enter.getEt_number());
		}
		enterDAO.saveList(temps);
		//3.删除临时表
		enterDAO.temp_clear(enter.getEt_type(), user.getUs_id(), user.getCompanyid());
	}
	
	@Override
	@Transactional
	public T_Buy_Enter approve(String number, T_Approve_Record record, T_Sys_User user,T_Sys_Set set) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Buy_Enter enter = enterDAO.check(number, user.getCompanyid());
		if(enter == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(enter.getEt_ar_state())){
			throw new RuntimeException("单据已经审核");
		}
		//1.更新单据审核状态
		enter.setEt_ar_state(record.getAr_state());
		enter.setEt_ar_date(DateUtil.getCurrentTime());
		enter.setEt_ar_name(user.getUs_name());
		enterDAO.updateApprove(enter);
		//2.保存审核记录表
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_buy_enter");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		if(!CommonUtil.AR_STATE_APPROVED.equals(enter.getEt_ar_state())){//审核不通过，则直接返回
			return enter;
		}
		//3.审核通过
		//3.1更新订单
		List<T_Buy_EnterList> details_order = enterDAO.listWithOrder(number, user.getCompanyid());
		if (details_order != null && details_order.size() > 0) {//更新订单子表和主表的已到数量
			Integer totalAmount_order = 0;
			String order_number = details_order.get(0).getEtl_order_number();
			for (T_Buy_EnterList item : details_order) {
				totalAmount_order += item.getEtl_amount();
			}
			T_Buy_Order order = enterDAO.loadOrder(order_number, user.getCompanyid());
			if(order != null){
				order.setOd_realamount(order.getOd_realamount()+totalAmount_order);
				Long days = DateUtil.getDaysMinusBetween(order.getOd_delivery_date(), DateUtil.getYearMonthDate());
				if (days > 0) {//超期
					order.setOd_state(order.getOd_realamount() >= order.getOd_amount() ? 3 : 4);
				}else {
					order.setOd_state(order.getOd_realamount() >= order.getOd_amount() ? 1 : 0);
				}
				enterDAO.updateOrder(order);
				enterDAO.updateOrderList(details_order);
			}
		}
		//3.2更新商品资料成本价
		if (enter.getEt_type().intValue() == 0) {// 进货入库
			List<T_Buy_EnterList> products = enterDAO.listGroupProduct(number, user.getCompanyid());//用etl_retailprice暂存pd_cost_price
			
			List<T_Base_Product> productList = new ArrayList<T_Base_Product>();
			T_Base_Product product = null;
			
			for (T_Buy_EnterList item : products) {
				product = new T_Base_Product();
				product.setPd_code(item.getEtl_pd_code());
				product.setPd_buy_price(item.getEtl_unitprice());
				product.setPd_buy_date(DateUtil.getYearMonthDate());
				product.setCompanyid(user.getCompanyid());
				productList.add(product);
			}
			enterDAO.updateProductBuyPriceAndDate(productList);
			
			
			if(set.getSt_buy_calc_costprice() != null && set.getSt_buy_calc_costprice().intValue() == 1){//启用进货使用加权平均算法修改成本价
				List<String> pd_codes = new ArrayList<String>();
				for(T_Base_Product item:productList){
					pd_codes.add(item.getPd_code());
				}
				List<T_Stock_DataBill> product_stocks = enterDAO.listProductStock(pd_codes, user);
				Map<String, Integer> stockMap = new HashMap<String, Integer>();
				Map<String, Double> stockPriceMap = new HashMap<String, Double>();
				for (T_Stock_DataBill stock : product_stocks) {
					stockMap.put(stock.getSd_pd_code(), stock.getSd_amount());
					stockPriceMap.put(stock.getSd_pd_code(), stock.getPd_cost_price());
				}
				int sd_amount = 0;
				double pd_cost_price = 0d;
				productList = new ArrayList<T_Base_Product>();
				for (T_Buy_EnterList item : products) {
					product = new T_Base_Product();
					product.setPd_code(item.getEtl_pd_code());
					product.setCompanyid(user.getCompanyid());
					sd_amount = 0;
					pd_cost_price = 0d;
					if(stockMap.containsKey(item.getEtl_pd_code())){
						sd_amount = stockMap.get(item.getEtl_pd_code());
						pd_cost_price = stockPriceMap.get(item.getEtl_pd_code());
					}
					if (item.getEtl_amount() + sd_amount == 0) {//进货入库后库存为0
						product.setPd_cost_price(item.getEtl_unitprice());
					}else {
						double price = (item.getEtl_amount()* item.getEtl_unitprice() + pd_cost_price * sd_amount)
								/ (item.getEtl_amount() + sd_amount);
						product.setPd_cost_price(Math.abs(price));
					}
					productList.add(product);
				}
				enterDAO.updateProductCostPrice(productList);
			}
		}
		
		//3.2更新库存
		List<T_Stock_DataBill> stocks = enterDAO.listStock(number, enter.getEt_depot_code(), user.getCompanyid());
		List<T_Stock_DataBill> add_stocks = new ArrayList<T_Stock_DataBill>();
		List<T_Stock_DataBill> update_stocks = new ArrayList<T_Stock_DataBill>();
		for (T_Stock_DataBill stock : stocks) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(enter.getEt_depot_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				if(enter.getEt_type().equals(0)){//进货
					stock.setSd_amount(stock.getBill_amount());
				}else {//退货
					stock.setSd_amount(-stock.getBill_amount());
				}
				add_stocks.add(stock);
			}else {
				if(enter.getEt_type().equals(0)){//进货
					stock.setSd_amount(stock.getSd_amount() + stock.getBill_amount());
				}else {//退货
					stock.setSd_amount(stock.getSd_amount() - stock.getBill_amount());
				}
				update_stocks.add(stock);
			}
		}
		if (add_stocks.size() > 0) {
			dataDAO.save(add_stocks);
		}
		if (update_stocks.size() > 0) {
			dataDAO.update(update_stocks);
		}
		//3.3更新供应商财务&生成往来明细账
		T_Buy_Supply supply = supplyDAO.loadSupply(enter.getEt_supply_code(), user.getCompanyid());
		if (supply != null) {
			supply.setSp_payable(supply.getSp_payable() + enter.getEt_payable());
			supplyDAO.updatePayable(supply);
			T_Buy_Dealings dealings = new T_Buy_Dealings();
			dealings.setDl_supply_code(enter.getEt_supply_code());
			dealings.setDl_number(enter.getEt_number());
			dealings.setDl_type(enter.getEt_type());
			dealings.setDl_discount_money(enter.getEt_discount_money());
			dealings.setDl_payable(enter.getEt_payable());
			dealings.setDl_payabled(0d);
			dealings.setDl_debt(supply.getSp_payable()-supply.getSp_payabled()-supply.getSp_prepay());
			dealings.setDl_date(DateUtil.getCurrentTime());
			dealings.setDl_manager(user.getUs_name());
			dealings.setDl_remark(enter.getEt_remark());
			dealings.setDl_sysdate(DateUtil.getCurrentTime());
			dealings.setDl_buyamount(enter.getEt_amount());
			dealings.setCompanyid(user.getCompanyid());
			buyDealingsDAO.save(dealings);
		}
		return enter;
	}
	
	@Override
	@Transactional
	public T_Buy_Enter reverse(String number, T_Sys_User user,T_Sys_Set set) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Buy_Enter enter = enterDAO.check(number, user.getCompanyid());
		if(enter == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_APPROVED.equals(enter.getEt_ar_state())){
			throw new RuntimeException("单据未审核或审核未通过");
		}
		if(!CommonUtil.PAY_STATE_UNPAY.equals(enter.getEt_pay_state())){
			throw new RuntimeException("该单据已经结算，不能反审核");
		}
		T_Buy_SettleList existSettle = buySettleDAO.check_settle_bill(enter.getEt_number(), user.getCompanyid());
		if(existSettle != null){
			throw new RuntimeException("该单据已经结算，结算单据["+existSettle.getStl_number()+"]，不能反审核");
		}
		//1.更新单据审核状态
		enter.setEt_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		enter.setEt_ar_date(DateUtil.getCurrentTime());
		enter.setEt_ar_name(user.getUs_name());
		enterDAO.updateApprove(enter);
		//2.保存审核记录表
		T_Approve_Record record = new T_Approve_Record();
		record.setAr_state(CommonUtil.AR_STATE_REVERSE_APPROVE);
		record.setAr_describe(user.getUs_name()+"反审核单据");
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_buy_enter");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		//3.1更新订单
		List<T_Buy_EnterList> details_order = enterDAO.listWithOrder(number, user.getCompanyid());
		if (details_order != null && details_order.size() > 0) {//更新订单子表和主表的已到数量
			Integer totalAmount_order = 0;
			String order_number = details_order.get(0).getEtl_order_number();
			for (T_Buy_EnterList item : details_order) {
				totalAmount_order += item.getEtl_amount();
			}
			T_Buy_Order order = enterDAO.loadOrder(order_number, user.getCompanyid());
			if(order != null){
				order.setOd_realamount(order.getOd_realamount()-totalAmount_order);
				Long days = DateUtil.getDaysMinusBetween(order.getOd_delivery_date(), DateUtil.getYearMonthDate());
				if (days > 0) {//超期
					order.setOd_state(order.getOd_realamount() >= order.getOd_amount() ? 3 : 4);
				}else {
					order.setOd_state(order.getOd_realamount() >= order.getOd_amount() ? 1 : 0);
				}
				enterDAO.updateOrder(order);
				enterDAO.updateOrderList_Reverse(details_order);
			}
		}
		
		//TODO 3.2更新商品资料成本价(???不需要更新成本价)
		//3.3更新库存
		List<T_Stock_DataBill> stocks = enterDAO.listStock(number, enter.getEt_depot_code(), user.getCompanyid());
		List<T_Stock_DataBill> add_stocks = new ArrayList<T_Stock_DataBill>();
		List<T_Stock_DataBill> update_stocks = new ArrayList<T_Stock_DataBill>();
		for (T_Stock_DataBill stock : stocks) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(enter.getEt_depot_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				if(enter.getEt_type().equals(0)){//进货
					stock.setSd_amount(-stock.getBill_amount());
				}else {//退货
					stock.setSd_amount(stock.getBill_amount());
				}
				add_stocks.add(stock);
			}else {
				if(enter.getEt_type().equals(0)){//进货
					stock.setSd_amount(stock.getSd_amount() - stock.getBill_amount());
				}else {//退货
					stock.setSd_amount(stock.getSd_amount() + stock.getBill_amount());
				}
				update_stocks.add(stock);
			}
		}
		if (add_stocks.size() > 0) {
			dataDAO.save(add_stocks);
		}
		if (update_stocks.size() > 0) {
			dataDAO.update(update_stocks);
		}
		//3.3更新供应商财务&删除往来明细账
		T_Buy_Supply supply = supplyDAO.loadSupply(enter.getEt_supply_code(), user.getCompanyid());
		if (supply != null) {
			supply.setSp_payable(supply.getSp_payable() - enter.getEt_payable());
			supplyDAO.updatePayable(supply);
			T_Buy_Dealings dealings = new T_Buy_Dealings();
			dealings.setDl_supply_code(enter.getEt_supply_code());
			dealings.setDl_number(enter.getEt_number());
			dealings.setDl_type(enter.getEt_type());
			dealings.setDl_discount_money(-enter.getEt_discount_money());
			dealings.setDl_payable(-enter.getEt_payable());
			dealings.setDl_payabled(0d);
			dealings.setDl_debt(supply.getSp_payable()-supply.getSp_payabled()-supply.getSp_prepay());
			dealings.setDl_date(DateUtil.getCurrentTime());
			dealings.setDl_manager(user.getUs_name());
			dealings.setDl_remark("反审核恢复账目往来明细");
			dealings.setDl_sysdate(DateUtil.getCurrentTime());
			dealings.setDl_buyamount(-enter.getEt_amount());
			dealings.setCompanyid(user.getCompanyid());
			buyDealingsDAO.save(dealings);
		}
		return enter;
	}
	
	@Override
	@Transactional
	public void initUpdate(String number,Integer et_type, Integer us_id, Integer companyid) {
		List<T_Buy_EnterList> details = enterDAO.detail_list_forsavetemp(number,companyid);
		for(T_Buy_EnterList item:details){
			item.setEtl_us_id(us_id);
		}
		enterDAO.temp_clear(et_type, us_id, companyid);
		enterDAO.temp_save(details);
	}
	
	@Override
	@Transactional
	public void del(String number, Integer companyid) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Buy_Enter enter = enterDAO.check(number, companyid);
		if(enter == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(enter.getEt_ar_state()) && !CommonUtil.AR_STATE_FAIL.equals(enter.getEt_ar_state())){
			throw new RuntimeException("单据已审核通过不能删除！");
		}
		enterDAO.del(number, companyid);
	}

	@Override
	public Map<String, Object> loadPrintData(String number, Integer sp_id, Integer displayMode, T_Sys_User user) {
		Map<String, Object> resultMap = printDAO.loadPrint4Bill(sp_id);
		T_Buy_Enter enter = enterDAO.load(number,user.getCompanyid());
		List<T_Buy_EnterList> enterList = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("etl_number", number);
		params.put("companyid", user.getCompanyid());
		if(displayMode.intValue() == 2){//汇总模式
			enterList = enterDAO.detail_sum(params);
		}else {
			enterList = enterDAO.detail_list_print(params);
		}
		resultMap.put("enter", enter);
		resultMap.put("enterList", enterList);
		resultMap.put("supply", supplyDAO.load(enter.getEt_supply_code(), user.getCompanyid()));
		System.out.println(enter.getEt_supply_code());
		if(displayMode.intValue() == 1){//尺码模式查询
			List<String> szgCodes = new ArrayList<String>();
			for (T_Buy_EnterList item : enterList) {
				if(!szgCodes.contains(item.getEtl_szg_code())){
					szgCodes.add(item.getEtl_szg_code());
				}
			}
			List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, user.getCompanyid());
			resultMap.put("sizeGroupList", sizeGroupList);
		}
		return resultMap;
	}

	@Override
	public List<T_Base_Barcode> print_barcode(Map<String, Object> params) {
		return enterDAO.print_barcode(params);
	}

}
